package com.wyt.common.properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 读取 properties 配置文件工具类
 */
public class YamlUtils {
    private static Logger logger = LoggerFactory.getLogger(YamlUtils.class);

    private static String path = null;
    static {
        //生产环境地址
        String rootPath = System.getProperty("user.dir");
        path = rootPath + File.separator + "config" + File.separator + "application.yml";
        File file = new File(path);
        //开发环境地址
        if (!file.exists()) path = YamlUtils.class.getClassLoader().getResource("application.yml").getPath();
        logger.info("yml文件路径path={}",path);
    }

    public static void updateYml(String key, Object value) throws Exception {
        Yaml yaml = new Yaml();
        try (FileInputStream fileInputStream = new FileInputStream(path)) {
            Map<String, Object> yamlMap = yaml.load(fileInputStream);
            if (key.contains(".")) {
                String[] keys = key.split("\\.");
                int i = 0;
                Map<String, Object> tmp = yamlMap;
                while (i < keys.length) {
                    if (i == keys.length - 1) break;
                    tmp = (Map<String, Object>) tmp.get(keys[i++]);
                }
                if (tmp != null) tmp.put(keys[keys.length - 1], value);
            } else {
                yamlMap.put(key, value);
            }
            try (FileWriter fileWriter = new FileWriter(path)) {
                fileWriter.write(yaml.dumpAsMap(yamlMap));
                fileWriter.flush();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            logger.error("更新yaml key={},value={}异常！\n", key, value, e);
        }
    }

    public static Object getYmlOrDefault(String key, Object defaultValue) {
        Object value = defaultValue;
        Yaml yaml = new Yaml();
        try (FileInputStream fileInputStream = new FileInputStream(path)) {
            Map<String, Object> yamlMap = yaml.load(fileInputStream);
            String[] split = key.split("\\.");
            for (int i = 0; i < split.length; i++) {
                if (i == split.length - 1) {
                    value = yamlMap.getOrDefault(split[i], defaultValue);
                } else {
                    yamlMap = (Map<String, Object>) yamlMap.getOrDefault(split[i], new HashMap<>());
                    if (yamlMap.size() == 0) break;
                }
            }
            logger.info("获取key={}的value为{}", key, value);
            return value;
        } catch (Exception e) {
            logger.error("获取key={}的值异常！", key, e);
        }
        return defaultValue;
    }

    public static void main(String[] args) {
        String path = File.separator + "opt" + File.separator + System.currentTimeMillis() + ".h264";
        if (System.getProperty("os.name").toLowerCase().startsWith("windows"))
            path = "D:\\tmp-data\\" + System.currentTimeMillis() + ".h264";
    }

}
